package leetcode.offer;

import leetcode.base.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * ClassName: BinaryTreeLevelOrderPrintII
 * Description: leetcode-剑指offer 32 - II. 从上到下打印二叉树II
 * date: 2021-11-02 8:59
 *
 * @author liyifan
 */
public class BinaryTreeLevelOrderPrintII {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if(root == null) {
            return new ArrayList<>();
        }
        ArrayList<List<Integer>> res = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            List<Integer> tempList = new ArrayList<>();
            for (int i = queue.size();i > 0;i--) {
                TreeNode temp = queue.poll();
                tempList.add(temp.val);
                if (temp.left != null)
                    queue.add(temp.left);
                if (temp.right != null){
                    queue.add(temp.right);
                }
            }
            res.add(tempList);
        }
        return res;
    }
}
